<?php
namespace app\admin\middleware;

use app\admin\model\AdminLog;
use app\admin\model\AuthGroup;
use app\admin\model\AuthRule;
use app\common\library\Auth;
use fast\Random;
use think\facade\Config;
use think\facade\Cookie;
use think\facade\Db;
use think\facade\Env;
use think\facade\Lang;
use think\facade\Session;
use think\facade\View;
use think\Request;
use think\Response;

class AuthUser
{
    protected $auth;

    public function __construct()
    {
        $this->auth = Auth::instance();
    }

    /**
     * 中间件执行入口
     *
     * @param Request $request
     * @param \Closure $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        $request->root(Config::get('app.http_type') . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['SCRIPT_NAME']), '/'));
        $pathinfo = $request->pathinfo();
        $path = strpos($pathinfo, '?') === false ? $pathinfo : strstr($pathinfo, '?', true);
        $controller = strtolower($request->controller());
        $action = strtolower($request->action());
        $controlleraction = strtolower("{$controller}/{$action}");

        // 检测是否需要验证登录
        if (!$this->auth->match(Config::get('fastadmin.notneedlogin'))) {
            // 检测是否登录
            if (!$this->auth->isLogin()) {
                $url = preg_replace_callback('/(\w)/', function ($match) {
                    return ucfirst($match[0]);
                }, $controlleraction);
                if ($request->isAjax()) {
                    return json(['code' => 401, 'msg' => __('Please login first'), 'url' => url('admin/login/index', ['redirect' => $url])]);
                } else {
                    $this->auth->setRedirectUrl($url);
                    return redirect(url('admin/login/index'));
                }
            }
        }

        // 检测是否需要验证权限
        if (!$this->auth->match(Config::get('fastadmin.notneedright'))) {
            // 检测是否有对应权限
            if (!$this->auth->check($controlleraction)) {
                if ($request->isAjax()) {
                    return json(['code' => 403, 'msg' => __('You have no permission')]);
                } else {
                    return view('public/error', ['msg' => __('You have no permission')]);
                }
            }
        }

        // 记录日志
        if ($this->auth->isLogin() && Config::get('fastadmin.log')) {
            AdminLog::record($path, $request->param());
        }

        // 渲染视图之前的参数赋值
        $view = View::assign([
            'admin'         => $this->auth->getUserInfo(),
            'site'          => Config::get("site"),
            'controllername' => $controller,
            'actionname'     => $action,
            'controlleraction' => $controlleraction,
            'jsname'        => substr($controller, 0, -1),
            'moduleurl'     => rtrim(url("/{$controller}", '', false), '/'),
            'language'      => Lang::getLangSet()
        ]);

        return $next($request);
    }
}